define(['./initial'], function() {
    var app = angular.module('App.tool');
    app.factory('bufferCaller', ["$q", "$timeout",
        function($q, $timeout) {
            var createBufferCaller = function(timeInterval) {
                timeInterval = timeInterval || 2800;
                var bufferCaller = {
                    fnBuffer: [],
                    running: false,
                    suspending: false,
                    _callFn: function(fn) {
                        var defer = $q.defer();
                        try {
                            if (!bufferCaller.suspending) {
                                fn();
                            }
                        } catch (err) {
                            console.log(err);
                        }
                        $timeout(function() {
                            defer.resolve();
                        }, timeInterval);
                        return defer.promise;
                    },
                    _callBuffer: function() {
                        if (bufferCaller.fnBuffer.length === 0) {
                            bufferCaller.running = false;
                            return;
                        }
                        var fn = bufferCaller.fnBuffer[0];
                        bufferCaller._callFn(fn).then(function() {
                            if (bufferCaller.fnBuffer.length > 0 && !bufferCaller.suspending) {
                                bufferCaller.fnBuffer.splice(0, 1);
                                bufferCaller._callBuffer();
                            } else {
                                return;
                            }
                        });
                    },
                    add: function(fn) {
                        bufferCaller.running = true;
                        bufferCaller.fnBuffer.push(fn);
                        if (bufferCaller.fnBuffer.length === 1) {
                            bufferCaller._callBuffer();
                        }
                    },
                    start: function() {
                        bufferCaller.suspending = false;
                        bufferCaller._callBuffer();
                    },
                    pause: function() {
                        bufferCaller.suspending = true;
                        if (bufferCaller.fnBuffer.length > 1) {
                            bufferCaller.fnBuffer.splice(0, 1);
                        }
                    },
                    cancel: function() {
                        bufferCaller.fnBuffer.length = 0;
                    }
                };
                return bufferCaller;
            };
            return createBufferCaller;
        }
    ]);
});
